package com.coincalf.exchange.task;

import com.coincalf.dto.MatchDTO;
import com.coincalf.exchange.entity.EntrustOrder;
import com.coincalf.exchange.entity.TurnoverOrder;
import com.coincalf.exchange.service.AccountService;
import com.coincalf.feign.MatchServiceClient;
import com.coincalf.framework.constants.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Map;

/**
 * @Description:
 * @Author: Chen Long
 * @Date: Created in 2018/6/1 下午6:27
 * @Modified by: Chen Long
 */
@Component
@Slf4j
public class AccountTask implements Constant {

    @Autowired
    private AccountService accountService;
    @Autowired
    private MatchServiceClient matchServiceClient;

    /**
     * 币币交易交易撮合
     *
     * @param matchResult 撮合结果
     */
    @Async("modifyAccountTaskAsyncPool")
    public void tradeMatchModifyAccount(Map<String, Object> matchResult) {
        long start = System.currentTimeMillis();
        TurnoverOrder dealOrder = (TurnoverOrder) matchResult.get(MATCH_RESULT_DEAL_ORDER);
        EntrustOrder buyOrder = (EntrustOrder) matchResult.get(MATCH_RESULT_BUY_ORDER);
        EntrustOrder sellOrder = (EntrustOrder) matchResult.get(MATCH_RESULT_SELL_ORDER);
        BigDecimal buyLock = (BigDecimal) matchResult.get(MATCH_RESULT_NEW_BUY_LOCK);
        BigDecimal sellLock = (BigDecimal) matchResult.get(MATCH_RESULT_NEW_SELL_LOCK);
        accountService.tradeMatchModifyAccount(dealOrder, buyOrder, sellOrder, buyLock, sellLock);
        // 更新缓存数据
        MatchDTO matchDTO = new MatchDTO();
        matchDTO.setSymbol(dealOrder.getSymbol())
                .setBuyUserId(dealOrder.getBuyUserId())
                .setSellUserId(dealOrder.getSellUserId());
        matchServiceClient.tradeMatch(matchDTO);
        long end = System.currentTimeMillis();
        log.info("币币交易撮合成功后修改资金账户、耗时：{} 毫秒", (end - start));
    }

}
